package com.changgou.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 *  拦截器是全局的，在调用feign之前都会执行
 * Created by zhangyuhong
 * Date:2020/org.slf4j5/18
 */
@Component
//微服务之间要互相调用,比如说订单微服务要调用商品goods微服务里的方法,所以需要传递token
public class MyFeignInterceptor implements RequestInterceptor {
    //路由里是通过过滤器转发token
     //request.mutate().header(AUTHORIZE_TOKEN,"bearer "+token);
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //1.通过上下文 获取当前的请求对象
        //该方法是从ThreadLocal变量里面取得相应信息的，当hystrix断路器的隔离策略为THREAD时，是无法取得ThreadLocal中的值。
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) return;
        HttpServletRequest request = requestAttributes.getRequest();
        //2.循环遍历获取请求对象中的头信息（authonrition的头的信息） 循环遍历所有的头信息 全部传递过去
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headName = headerNames.nextElement();
            String headerValue = request.getHeader(headName);
            //3.再调用feign之前将头添加到Http当中传递给下游微服务
            requestTemplate.header(headName, headerValue);
        }
    }
}
